<template>
  <div class="my-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="openDialog()">
      <img :src="coverImageUrl" />
    </div>
    <!-- 对话框 -->
    <el-dialog
      :append-to-body="true"
      :visible.sync="dialogVisible"
      width="720px">
      <!-- tab组件 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="images">
            <div style="padding-bottom: 20px;">
                <el-radio-group v-model="isCollected" size="mini"  @change="hToggle">
                    <el-radio-button :label="false">全部</el-radio-button>
                    <el-radio-button :label="true">收藏</el-radio-button>
                </el-radio-group>
            </div>
            <!-- 素材列表 -->
            <el-row :gutter="10" class="img_list">
                <el-col class="img_item " :xs="12" :sm="6" :md="6" :lg="4"
                  v-for="images in images" :key="images.id"
                   @click.native="hSelectImage(images.url)"
                   :class="{selected : images.url === selectedImageUrl}"
                   >
                    <el-image
                        style="height: 100px;"
              :src="images.url"
                        fit="cover"></el-image>
                </el-col>
            </el-row>
            <!-- /素材列表 -->
            <!-- 分页组件 -->
            <el-pagination
                          background
                          layout="prev, pager, next"
                           @current-change="hPageChange"
                          :total="totalCount">
            </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
           <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="hbeforeAvatarUpload"
          >
            <el-image v-if="uploadImageUrl" :src="uploadImageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="hConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '@/assets/default.png'
export default {
  name: 'MyCover',
  props: ['value'],
  data () {
    return {
      coverImageUrl: this.value || defaultImg,
      // 控制对话框显示隐藏
      dialogVisible: false,
      // 当前tabs组件激活的选项卡的name属性的值
      activeName: 'image',
      images: [],
      curPage: 1, // 当前的页码
      totalCount: 0, // 一共有几条
      isCollected: false,
      selectedImageUrl: '', // 记录当前用户选中的图片地址
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      uploadImageUrl: ''// 上传成功之后的预览图片地址
    }
  },
  methods: {
    openDialog () {
      this.dialogVisible = true
      this.loadImages()
    },
    // 发送请求获取数据
    async loadImages () {
      try {
        const res = await this.$http({
          url: '/mp/v1_0/user/images',
          method: 'GET',
          params: {
            per_page: 10, // 固定每页只取回10条
            collect: this.isCollected, // 是否是收藏的图片
            page: this.curPage
          }
        })
        this.images = res.data.data.results
        this.totalCount = res.data.data.total_count
      } catch (err) {
        console.log(err)
        this.$message.error('获取信息失败')
      }
    },
    // 切换收藏全部功能
    hToggle () {
      this.curPage = 1
      this.loadImages()
    },
    // 点击分页功能
    hPageChange (page) {
      this.curPage = page
      this.loadImages()
    },
    // 选中状态功能
    hSelectImage (url) {
      this.selectedImageUrl = url
    },
    // 上传成功之后
    handleAvatarSuccess (res, file) {
      // res中保存着本次上传操作成功后，后端接口返回的数值
      // 1. 预览效果
      this.uploadImageUrl = res.data.url
      this.$message.success('上传成功')
    },
    // 图片上传之前做一些检验
    hbeforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 点击确定上传
    hConfirm () {
      if (this.activeName === 'images') {
        if (this.selectedImageUrl) {
          this.coverImageUrl = this.selectedImageUrl
        } else {
          this.$message.error('请选择图片')
        }
      } else {
        if (this.uploadImageUrl) {
          this.coverImageUrl = this.uploadImageUrl
        } else {
          this.$message.error('请选择图片')
        }
      }
      this.dialogVisible = false
      this.$emit('input', this.coverImageUrl)
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  cursor: pointer;
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
// 素材列表
.img_list{
  margin-top: 15px;
  .img_item{
    width: 150px;
    height: 120px;
    border: 1px dashed #ddd;
    display: inline-block;
    margin-right: 15px;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
}
.selected::after{
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3) url(../assets/selected.png) no-repeat center / 50px 50px;
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
</style>
